package xml
{
	import events.MyEvent;
	
	import flash.errors.IOError;
	import flash.events.*;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.*;
	/**
	 * ...
	 * @author FireKnight
	 */
	public class XMLLoad extends EventDispatcher
	{
		private var myXML:XML;
		private var myXmlLoader:URLLoader;
		private var myRequest:URLRequest;
		private var myFunction:Function;
		public const FORMAT_ERROR:String="format_error";
		public const IO_ERROR:String = "io_error";
		private var xml_url:String;
		public function XMLLoad()
		{

		}

		public function init(url:String, complete:Function):void
		{
			
			removeXmlLoader();
			xml_url = url;
			myFunction = complete;
			myXmlLoader = new URLLoader () ;
			myRequest = new URLRequest(url);
			myXmlLoader.load(myRequest);
			myXmlLoader.addEventListener(Event.COMPLETE, handleComplete);
			myXmlLoader.addEventListener(IOErrorEvent.IO_ERROR, handleIoError);
		}

		private function handleComplete(e:Event):void
		{
			try
			{
				myXML = new XML(e.target.data);
				//trace(e.target.data);
			}
			catch (ev:Error)
			{

				trace(xml_url+"格式错误=" + e, e.type);
				this.dispatchEvent(new MyEvent(FORMAT_ERROR,xml_url+"格式错误"));
				return;
				
			}
			
			myFunction(e);
			myXmlLoader.removeEventListener(Event.COMPLETE, handleComplete);
			myXmlLoader.removeEventListener(IOErrorEvent.IO_ERROR, handleIoError);

		}//end handleComplete

		private function handleIoError(e:IOErrorEvent):void
		{
			trace("未找到");
			myXmlLoader.removeEventListener(Event.COMPLETE, handleComplete);
			myXmlLoader.removeEventListener(IOErrorEvent.IO_ERROR, handleIoError);
			this.dispatchEvent(new MyEvent(IO_ERROR,xml_url+"未找到"));
			return;
		}//end handleIoError

		private function removeXmlLoader():void
		{
			if (myXmlLoader)
			{
				myXmlLoader = null;
			}
		}//end removeXmlLoader

	}

}